import { create } from 'zustand';
import { RouteType } from '@/router/type';
import type { MenuProps } from 'antd';

export type MenuItem = Required<MenuProps>['items'][number];
interface MenuState {
  menus: MenuItem[];
  getMenus: (routes: RouteType[]) => void;
}

export const useMenu = create<MenuState>(set => ({
  menus: [],
  getMenus: (routes: RouteType[]) => {
    let menus: MenuItem[] = [];
    function getChildren(menus: RouteType[]): MenuItem[] {
      let result: MenuItem[] = [];
      if (!menus || !menus.length) {
        return [];
      }
      for (let i = 0; i < menus.length; i++) {
        if (menus[i].handle.hide) {
          continue;
        }
        let menuItem = menus[i];
        let key = menuItem.path !== '/' ? menuItem.path : menuItem.handle.key;
        let icon = menuItem.handle.icon;
        // let selectedIcon = menuItem.handle.selectedIcon;
        let children = undefined;
        if (menuItem.children && menuItem.children.length > 0) {
          children = getChildren(menuItem.children as RouteType[]);
        }
        let label = menuItem.handle.title;
        let type = menuItem.handle.type;
        result.push({
          key,
          icon,
          // default: icon,
          // selectedIcon,
          children,
          label,
          type,
        } as MenuItem);
      }
      return result;
    }
    menus = getChildren(routes) as MenuItem[];
    set({ menus });
  },
}));
